package com.frx.leetoffer.link;

/**
 * Created with IDEA
 *
 * @author: xrf
 * @Date: 2019/10/9
 * @Time: 19:50
 */
public class LinkCircle {

    public static void main(String[] args){
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node3;
        System.out.println(isCircle(node1));
        System.out.println(findCircle(node1));
    }

    public static boolean isCircle(Node node){
        Node p1 = node;
        Node p2 = node;
        while (p2 != null && p2.next != null){
            p1 = p1.next;
            p2 = p2.next.next;
            if (p1 == p2){
                return true;
            }
        }
        return false;
    }

    /**
     * @description 寻找入环点
     * @param head
     * @return
     */
    public static int findCircle(Node head){
        Node fast = head.next.next;
        Node slow = head.next;
        while (fast != slow){
            slow = slow.next;
            fast = fast.next.next;
        }
        fast = head;
        while (fast != slow){
            fast = fast.next;
            slow = slow.next;
        }

        return slow.val;
    }

    private static class Node{
        int val;
        Node next;
        public Node(int val){
            this.val = val;
        }
    }


}
